package com.diamond.listener;

import com.diamond.pojo.ProductType;
import com.diamond.service.ProductTypeService;
import com.diamond.service.impl.ProductTypeServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.List;

/**
 * 用servletContext监听器处理是因为多个界面需要在界面初始化之前就获取好数据
 */
@WebListener
public class ProductTypeListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        //Spring IOC容器也是用listener初始化，所以不能判断哪个监听器先注册直接手动初始化
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext_*.xml");
        ProductTypeService service = (ProductTypeService) context.getBean("productTypeServiceImpl");
        List<ProductType> types = service.getAll();
        //放入servletContext域中让新增、修改页面共享数据
        ServletContext servletContext = servletContextEvent.getServletContext();
        servletContext.setAttribute("types",types);
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
}
